<template>
    <div class="bg">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <span>发布文章</span>
                </div>
            </template>
            <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="form.description" :rows="2" type="textarea" placeholder="请输入描述" />
                </el-form-item>
                <el-form-item prop="cate_1st" label="分类" >
                    <el-select v-model="form.cate_1st" prop="cate_1st" class="m-2" placeholder="请选择1类型">
                        <el-option v-for="item in option_1st" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                    <el-form-item prop="cate_2nd" >
                    <el-select v-model="form.cate_2nd" prop="cate_2nd" class="m-2" placeholder="请选择2类型">
                        <el-option v-for="item in option_2nd" :key="item.id" :label="item.name"  :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="main_photo" label="主图">
                    <el-upload action="http://localhost:3001/upload/common/" :data="extra" size="small" :headers="headers"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" 
                        :on-error="handleUploadError" :show-file-list="false" accept=".jpg,.jpeg,.png"
                        class="avatar-uploader">
                        <img v-if="form.main_photo" :src="form.main_photo" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <div style="border: 1px solid #ccc;width: 100%">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 500px; overflow-y: hidden;" v-model="form.content"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
                <el-form-item>
                <el-button @click="handleSubmit(formRef)" type="primary">
                    发布文章
                </el-button>
            </el-form-item>
            </el-form>
         
        </el-card>
    </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Plus } from '@element-plus/icons-vue';
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive,watch } from 'vue'
import Article from '@/api/article';
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
//获取form表单实例化对象
let formRef = ref();
//提取token
let token = sessionStorage.token;
let headers = { Authorization: `Bearer ${token}` };
//附带参数
let extra = { type: 'common' };
let form = reactive({
    title:"",
    description:'',
    cate_1st:'',
    cate_2nd:'',
    main_photo:'',
    content:'',
});
const handleAvatarSuccess = ({ status, msg, src }, uploadFile) => {
    //    console.log(response,uploadFile)
    //上传成功
    if (status) {
        //生成图片地址，预览图片
        form.main_photo = src;
        ElMessage.success(msg);
    } else {
        //上传失败 
        ElMessage.error(msg);
    }
}
const handleUploadError = (error, uploadFile) => {
    console.dir(error)
    let { status, msg } = JSON.parse(error.message);
    ElMessage.error(msg);

};
//加载所有分类列表
// let roles = ref([]);
let loadListson = async (id) => {
    let { status, msg, data } = await Article.son({id});
    if (status) {
     return data;
    }
};

//请求子级分类
let option_1st = ref([]);
//二级分类
let option_2nd = ref([]);
onMounted(async()=>{
    //请求一级分类
  option_1st.value = await loadListson(0);


});
//监听一级分类，请求二级分类
watch(()=>form.cate_1st,async(newValue,oldValue)=>{
// console.log(newValue)
   option_2nd.value=await loadListson(newValue);
     //默认选中第一项
  form.cate_2nd = option_2nd.value[0].id;
})
const beforeAvatarUpload = (rawFile) => {
    //判断图片格式/^image\/[jepg|png|jpg]$/
    let isValid = /^image\/(jpeg|png|jpg)$/.test(rawFile.type);
    if (!isValid) {
        ElMessage.error('头像必须是jpg/png格式!!!')
        return false
    }
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
const toolbarConfig = {}
const mode = ref('simple')
// 表单验证规则
const rules = reactive({
    title: [
        { required: true, message: '请输入标题内容！', trigger: 'blur' },

    ],
    description: [
        { required: true, message: '请输入描述！', trigger: 'blur' },
    ],
    cate_1st: [
        { required: true, message: '请选择类型！', trigger: 'blur' },
    ],
    cate_2nd: [
        { required: true, message: '请选择类型！', trigger: 'blur' },
    ],
   main_photo: [
        { required: true, message: '请放入主图！', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入内容！', trigger: 'blur' },
    ],
});
// 发布新文章
function handleSubmit(formEl) {
    // 校验整个表单
    formEl.validate(async (valid) => {
        if (valid) {
            // 通过校验
            let { status, msg, data } = await Article.release({ ...form });
            if (status) {
                ElMessage.success(msg);

            } else {
                ElMessage.error(msg);
            }

        }
    });
}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
}
//上传图片配置
editorConfig.MENU_CONF['uploadImage'] = {
    // form-data fieldName ，默认值 'wangeditor-uploaded-image'
    fieldName: 'file',
    server: 'http://localhost:3001/upload/editor/',
    headers: {
        Authorization: `Bearer ${sessionStorage.token}`,
    },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
//创建阶段
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
</script>
<style scoped>
    .avatar-uploader .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    </style>
<style>
    .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>